<script setup lang="ts">
import {
  createRentAPI,
  getEnterpriseListAPI,
  getRentBuildListAPI,
  getRentListAPI,
  outRentAPI,
  uploadAPI,
} from "@/apis/enterprise";
import type {
  Datum,
  Enterprise,
  EnterpriseListParams,
} from "@/types/enterprise";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type TagProps,
  type UploadInstance,
  type UploadRawFile,
  type UploadRequestOptions,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";

// 查询参数
const queryParams = reactive<EnterpriseListParams>({
  name: "", // 企业名称
  page: 1, // 页码
  pageSize: 10, // 页大小
});

// 带合同的企业信息
interface EnterpriseWithRent extends Enterprise {
  rentList: Datum[];
}

// 表格数据
const tableData = ref<EnterpriseWithRent[]>([]);
// 总条数
const totalCount = ref(0);
// 获取列表数据
const getList = async () => {
  // 发送请求
  const res = await getEnterpriseListAPI(queryParams);
  console.log(res);
  // 保存表格数据
  tableData.value = res.data.rows.map((item) => {
    return {
      ...item,
      rentList: [] as Datum[], // 每一行补充存放合同的列表
    };
  });
  // 保存分页数据
  totalCount.value = res.data.total;
};

// 页面加载获取数据
onMounted(() => {
  getList();
});

// 查询搜索
const onSubmit = () => {
  // 重置页码
  queryParams.page = 1;
  // 重新获取数据
  getList();
};

const dialogVisible = ref(false);

// 可租赁楼宇列表
const buildList = ref<{ id: string; name: string }[]>([]);
// 添加合同
const addRent = async (id: string) => {
  // 弹出对话框
  dialogVisible.value = true;
  // 获取可租赁楼宇列表
  const res = await getRentBuildListAPI();
  buildList.value = res.data;
  // 把企业 id 添加到 合同表单中
  rentForm.enterpriseId = id;
};

// 添加合同表单
const rentForm = reactive({
  buildingId: "", // 楼宇id
  contractId: "", // 合同id
  contractUrl: "", // 合同Url
  enterpriseId: "", // 企业名称
  type: 0, // 合同类型
  rentTime: [], // 合同时间
});

// 合同表单校验
const rentRules = ref<FormRules<typeof rentForm>>({
  buildingId: [{ required: true, message: "请选择楼宇", trigger: "change" }],
  rentTime: [{ required: true, message: "请选择租赁日期", trigger: "change" }],
  contractId: [{ required: true, message: "请上传合同文件" }],
});

// 合同表单统一校验用的实例
const addFormRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();

const onClose = () => {
  // 关闭对话框
  dialogVisible.value = false;
  // 重置表单
  addFormRef.value?.resetFields();
  // 清空上传组件的文件信息
  uploadRef.value?.clearFiles();
  // 清空合同信息
  rentForm.contractUrl = "";
  rentForm.contractId = "";
};
// 提交合同表单
const onSubmitRent = async () => {
  try {
    // 表单校验
    await addFormRef.value?.validate();
    // 提交表单
    await createRentAPI({
      buildingId: rentForm.buildingId,
      startTime: rentForm.rentTime[0],
      endTime: rentForm.rentTime[1],
      contractUrl: rentForm.contractUrl,
      contractId: rentForm.contractId,
      type: rentForm.type,
      enterpriseId: rentForm.enterpriseId,
    });
    // 轻提示
    ElMessage.success("添加合同成功");
    // 关闭对话框，需要重置表单和上传组件
    onClose();
  } catch (error) {
    ElMessage.error("请填写完整信息");
  }
};

// 上传前校验
const beforeUpload = (rawFile: UploadRawFile) => {
  // 大小限制：5M
  const size5M = 5 * 1024 * 1024;
  // 格式限制：.png .jpg .jpeg
  const AcceptType = ["application/msword", "application/pdf"];
  if (rawFile.size > size5M) {
    ElMessage.error("文件大小不能超过5M");
    return false;
  } else if (AcceptType.includes(rawFile.type) === false) {
    ElMessage.error("仅支持扩展名为 .pdf, .doc 的合同");
    return false;
  }
};
// 删除了文件
const onFileRemove = () => {
  // 清空合同信息
  rentForm.contractId = "";
  rentForm.contractUrl = "";
};
// 上传合同
const uploadHttpRequest = async (options: UploadRequestOptions) => {
  // 准备 fromData 请求体参数(前端上传文件需要用 formData 处理成二进制数据上传)
  const formData = new FormData();
  formData.append("file", options.file);
  formData.append("type", "contract");
  // 上传租赁合同
  const res = await uploadAPI(formData);
  console.log("上传合同成功", res);
  // 保存租赁合同 id 和 url
  rentForm.contractId = res.data.id;
  rentForm.contractUrl = res.data.url;
  // 主动触发校验(校验通过，错误提示就会消失)
  addFormRef.value?.validateField("contractId");
};

// 展开行触发
const expandHandle = async (row: EnterpriseWithRent) => {
  // 根据企业 id 获取合同列表
  const res = await getRentListAPI(String(row.id));
  // 把合同列表添加到企业信息中
  row.rentList = res.data;
  console.log("当前企业的合同列表", res.data);
};

//                     0        1        2        3
const rentStatus = ["待生效", "生效中", "已到期", "已退租"];
// el-tag 类型列表
const tagTypes: TagProps["type"][] = ["primary", "success", "warning", "info"];

// 点击退租按钮
const outRent = async (row: Datum) => {
  console.log(row.id);
  try {
    await ElMessageBox.confirm("确认退租吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 发送退租请求
    await outRentAPI(row.id);
    // 轻提示
    ElMessage.success("退租成功");
    // 乐观UI更新：前端做视图更新即可，无需再发送请求获取整合列表
    row.status = 3;
    // 重新合同列表
  } catch (error) {}
};
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        v-model="queryParams.name"
        clearable
        placeholder="请输入内容"
        class="search-main"
        @clear="onSubmit"
      />
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">
        添加企业
      </el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="tableData"
        @expand-change="expandHandle"
        row-key="id"
      >
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
                :align="'center'"
              />
              <el-table-column label="租赁起始时间" :align="'center'">
                <template #default="{ row }">
                  {{ row.startTime + " 至 " + row.endTime }}
                </template>
              </el-table-column>
              <!--
              合同的租赁状态：
                0待生效 1生效中 2已到期 3已退租
              补充：
                生效中，只能续签一次，续签后，续签的合同退租后，才可以退租 
              -->
              <el-table-column label="合同状态">
                <template #default="{ row }">
                  <el-tag :type="tagTypes.at(row.status)">
                    {{ rentStatus.at(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="280" align="center">
                <template #default="{ row }">
                  <el-button
                    :disabled="[1, 3].includes(row.status)"
                    size="small"
                    type="text"
                  >
                    续租
                  </el-button>
                  <el-button
                    :disabled="[3].includes(row.status)"
                    size="small"
                    type="text"
                    @click="outRent(row)"
                  >
                    退租
                  </el-button>
                  <el-button
                    :disabled="![3].includes(row.status)"
                    size="small"
                    type="text"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="320">
          <template #default="{ row: enterprise }">
            <el-button size="small" type="text" @click="addRent(enterprise.id)">
              添加合同
            </el-button>
            <el-button
              @click="$router.push('/exterpriseDetail?id=' + enterprise.id)"
              size="small"
              type="text"
            >
              查看
            </el-button>
            <el-button size="small" type="text">编辑</el-button>
            <el-button size="small" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="totalCount"
        :page-sizes="[2, 5, 10, 20]"
        v-model:page-size="queryParams.pageSize"
        v-model:current-page="queryParams.page"
        layout="sizes, total, prev, pager, next, jumper"
        @current-change="getList"
        @size-change="getList"
      />
    </div>
    {{ queryParams }}
  </div>
  <el-dialog
    title="添加合同"
    width="600px"
    v-model="dialogVisible"
    @close="onClose"
  >
    <!-- 表单模版 -->
    <div class="form-container">
      <el-form
        ref="addFormRef"
        :model="rentForm"
        :rules="rentRules"
        label-position="top"
      >
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="rentForm.buildingId" placeholder="请选择">
            <el-option
              v-for="item in buildList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="rentTime">
          <el-date-picker
            v-model="rentForm.rentTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload
            ref="uploadRef"
            action="#"
            accept=".pdf, .doc"
            :http-request="uploadHttpRequest"
            :before-upload="beforeUpload"
            :on-remove="onFileRemove"
          >
            <el-button size="small" type="primary" plain>
              上传合同文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.doc .pdf, 文件大小不超过5M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      {{ rentForm }}
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button @click="onSubmitRent" type="primary">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
